import type { FormInstance } from 'element-plus'
import type {
  facilityTypeEnum,
  suborinateLampPostEnum
} from '~/store/assetManagement/facilityManagement/typings'
import type { AssetLampBaseDataItemType } from '../../facilityManagement/assetLampBase/typings'
import type { AssetHomeMarkerData } from '../map/typings'
import type { LampPopoverPropsType, LampPopoverStateType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElPopover,
  ElCard,
  ElRow,
  ElCol,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElForm,
  ElFormItem,
  ElDescriptions,
  ElDescriptionsItem,
  ElLink,
  ElButton,
  ElInput,
  ElSelect,
  ElOption,
  ElSwitch,
  ElMessage,
  ElIcon,
  ElSpace,
  ElImage,
  ElTooltip
} from 'element-plus'
import { CaretBottom } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import useVuexGetters from '~/hooks/useVuexGetters'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'LampPopover',
  props: ['left', 'top', 'popoverInfo', 'pointList', 'changeActivePatternMarker', 'onCancel'],
  setup(props: LampPopoverPropsType) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const disabledDeliverRef = ref<boolean>()
    const state = reactive<LampPopoverStateType>({
      isEdit: false,
      loading: false,
      distributionSelectList: []
    })
    const formValues = reactive<AssetLampBaseDataItemType>({})
    const assetLampBaseState = useVuexGetters('assetLampBase', ['lampBaseTypeSelectList']) // 灯具类型
    const assetLampPostState = useVuexGetters('assetLampPost', ['suborinateLampPostSelectList']) // 所属灯杆

    // 获取灯杆下拉列表
    const handleSearchLightPoleSelectList = (detail: AssetLampBaseDataItemType) => {
      const params = {
        distributionId: formValues.distributionId,
        workAreaId: detail.workAreaId,
        streetId: detail.streetId,
        key: ''
      }
      store.dispatch('assetLampPost/GetLampPostSelectBoxListByKey', params) // 获取所属灯杆下拉列表
    }

    // 修改是否编辑状态
    const handleChangeIsEditStatus = async () => {
      if (!state.isEdit) {
        state.loading = true
        const result = await store.dispatch('assetLampBase/GetAssetLampBaseInfo', {
          id: props?.popoverInfo?.assetId
        })
        if (result?.data) {
          Object.assign(formValues, result?.data, {
            isDeliver: !!result?.data?.isDeliver
          })
          // 设置编辑时投运状态是否禁用
          disabledDeliverRef.value = !!result?.data?.isDeliver
          handleSearchLightPoleSelectList(result?.data)
          state.isEdit = !state.isEdit
        }
        state.loading = false
        return
      }
      state.isEdit = !state.isEdit
    }

    // 提交修改
    const handleSubmitUpdateLampInfo = () => {
      ruleFormRef.value!.validate(async (valid: boolean) => {
        if (!valid) return
        state.loading = true
        const params = { ...formValues }
        params.name = handleTrim(params.name!)
        params.isDeliver = params.isDeliver ? 1 : 0
        const res = await store.dispatch('assetLampBase/UpdateAssetLampBaseInfo', params)
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          props.onCancel!()
          // handleChangeIsEditStatus()
        }
        state.loading = false
      })
    }

    // 获取所属配电设施下拉列表
    const getDistributionSelectBoxList = async () => {
      const res = await store.dispatch('powerDistributionFacilities/GetDistributionSelectBoxList')
      state.distributionSelectList = res.data || []
    }

    // 修改配电设施时
    const handleChangeDistribution = () => {
      formValues.lampPostId = undefined
      handleSearchLightPoleSelectList(formValues)
    }

    // 切换重合点信息弹框
    const handleChangePointInfo = (record: AssetHomeMarkerData) => {
      props.changeActivePatternMarker(record)
    }

    onMounted(() => {
      getDistributionSelectBoxList()
    })

    return () => (
      <ElPopover
        visible
        placement="bottom"
        teleported={false}
        popperClass={styles['asset-home-info-popover']}
        {...{
          // virtualRef: props.dom,
          virtualRef: {
            getBoundingClientRect() {
              return DOMRect.fromRect({
                width: 0,
                height: 0,
                x: props.left,
                y: props.top
              })
            }
          },
          virtualTriggering: true
        }}
      >
        <ElCard
          class={styles['asset-home-light-pole-info-card']}
          shadow="never"
          v-slots={{
            header: () => (
              <ElRow>
                <ElCol span={20}>
                  {state.isEdit && '修改'}
                  {!state.isEdit && !props?.pointList?.length && props?.popoverInfo?.name}
                  {!state.isEdit && !!props?.pointList?.length && (
                    <ElDropdown
                      trigger="click"
                      onCommand={handleChangePointInfo}
                      v-slots={{
                        dropdown: () => (
                          <ElDropdownMenu>
                            {props?.pointList?.map((item) => (
                              <ElDropdownItem command={item}>{item.name}</ElDropdownItem>
                            ))}
                          </ElDropdownMenu>
                        )
                      }}
                    >
                      <section>
                        <ElTooltip content={props?.popoverInfo?.name}>
                          {props?.popoverInfo?.name}
                        </ElTooltip>
                        {props?.pointList?.length && (
                          <ElIcon>
                            <CaretBottom />
                          </ElIcon>
                        )}
                      </section>
                    </ElDropdown>
                  )}
                </ElCol>
                <ElCol span={4} {...{ align: 'right' }}>
                  {!state.isEdit && (
                    <>
                      <ElLink
                        type="primary"
                        icon={<AliIcon type="icon-bianji" />}
                        // loading={loadingRef.value}
                        onClick={handleChangeIsEditStatus}
                      />
                      &emsp;
                    </>
                  )}
                  <ElLink
                    class={styles['asset-home-info-popover-close']}
                    underline={false}
                    onClick={props.onCancel}
                  >
                    <AliIcon type="icon-danchuang-guanbi" />
                  </ElLink>
                </ElCol>
              </ElRow>
            )
          }}
        >
          {state.isEdit ? (
            <ElForm ref={ruleFormRef} model={formValues} labelWidth="100px" labelPosition="right">
              <ElFormItem
                prop="isDeliver"
                label="投运状态"
                rules={[{ required: false, message: '请输入投运状态' }]}
              >
                <ElSwitch v-model={formValues.isDeliver} disabled={disabledDeliverRef.value} />
              </ElFormItem>
              <ElFormItem
                prop="name"
                label="设施名称"
                rules={[
                  { required: false, whitespace: true, message: '请输入设施名称' },
                  { min: 3, whitespace: true, message: '设施名称长度为3～20字符' }
                ]}
              >
                <ElInput v-model={formValues.name} {...{ minlength: 3, maxlength: 20 }} />
              </ElFormItem>
              <ElFormItem
                prop="categoryId"
                label="设施类型"
                rules={[{ required: false, message: '请选择设施类型' }]}
              >
                <ElSelect v-model={formValues.categoryId}>
                  {assetLampBaseState.lampBaseTypeSelectList?.value?.map(
                    (item: facilityTypeEnum) => (
                      <ElOption key={item?.id} label={item?.title} value={item?.id!} />
                    )
                  )}
                </ElSelect>
              </ElFormItem>
              <ElFormItem
                prop="distributionId"
                label="所属配电设施"
                rules={[{ required: false, message: '请选择所属配电设施' }]}
              >
                <ElSelect v-model={formValues.distributionId} onChange={handleChangeDistribution}>
                  {state.distributionSelectList?.map((item) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                  ))}
                </ElSelect>
              </ElFormItem>
              <ElFormItem
                prop="lampPostId"
                label="所属灯杆"
                rules={[{ required: false, message: '请选择所属灯杆' }]}
              >
                <ElSelect v-model={formValues.lampPostId}>
                  {assetLampPostState.suborinateLampPostSelectList?.value?.map(
                    (item: suborinateLampPostEnum) => (
                      <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                    )
                  )}
                </ElSelect>
              </ElFormItem>
              <div {...({ align: 'right' } as any)}>
                <ElButton onClick={handleChangeIsEditStatus}>取消</ElButton>
                <ElButton
                  type="primary"
                  loading={state.loading}
                  onClick={handleSubmitUpdateLampInfo}
                >
                  保存
                </ElButton>
              </div>
            </ElForm>
          ) : (
            <ElDescriptions column={1}>
              {props?.popoverInfo?.infoList?.map((item) => (
                <ElDescriptionsItem label={item.key}>
                  {item.type === 'text' && item.value}
                  {item.type === 'image' && item.value && typeof item.value === 'string' && (
                    <ElSpace>
                      {item.value?.split(',')?.map((url: string, index: number, arr: string[]) => (
                        <ElImage
                          class={styles['asset-home-light-info-image']}
                          src={url}
                          previewSrcList={arr}
                          initialIndex={index}
                          previewTeleported
                        />
                      ))}
                    </ElSpace>
                  )}
                </ElDescriptionsItem>
              ))}
              {/* <ElDescriptionsItem align="right">
                <ElButton type="primary" loading={state.loading} onClick={handleChangeIsEditStatus}>
                  编辑
                </ElButton>
              </ElDescriptionsItem> */}
            </ElDescriptions>
          )}
        </ElCard>
      </ElPopover>
    )
  }
})
